import { UserState } from "@/api/user/types";
import { constantRoutes } from "@/router/routes";
import { defineStore } from "pinia";
// 引入Api
import { userLoginApi, userInfoApi, userLogoutApi } from "@/api/user/index.ts";

// 创建用户小仓库
const useUserStore = defineStore("User", {
  // 小仓库存储数据地方
  state: (): UserState => {
    return {
      token: "",
      menuRoutes: constantRoutes,
      username: "",
      avatar: "",
      buttons: [],
    };
  },
  // 异步逻辑的地方
  actions: {
    // 第二种：Axios请求MockJS数据（二次封装）Api优化版之Pinia状态管理库版
    async userLoginAction(data: any, headers?: any) {
      const response = await userLoginApi(data, headers);
      if (response.code === 200) {
        if (response.data) {
          this.token = response.data;
        }
      }
      return response;
    },
    // 第二种：Axios请求MockJS数据（二次封装）Api优化版之Pinia状态管理库版
    async userInfoAction(params?: any, headers?: any) {
      const response = await userInfoApi(params, headers);
      if (response.code === 200) {
        if (response.data.checkUser) {
          this.avatar = response.data.checkUser.avatar;
          this.username = response.data.checkUser.desc;
        }
      }
      return response;
    },
    // 第二种：Axios请求MockJS数据（二次封装）Api优化版之Pinia状态管理库版
    async userLogoutAction(params?: any, headers?: any) {
      const response = await userLogoutApi(params, headers);
      if (response.code === 200) {
        if (response.message === "success") {
          // 用户登录接口赋值字段清空值吧
          this.token = "";
          // 用户信息接口赋值字段清空值吧
          this.avatar = "";
          this.username = "";
        }
      }
      return response;
    },
  },
  getters: {},
});

// 对外暴露获取小仓库的方法
export default useUserStore;
